package com.tcm.utils;

import cn.hutool.poi.excel.ExcelWriter;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;

/**
 * Excel导出工具类
 * @author Guqier
 * @version 1.0
 * @date 2023/8/4 14:11
 */
public class ExcelExportUtil {

    /**
     * 通用导出
     * @param writer ExcelWriter
     * @param response HttpServletResponse
     * @throws IOException IO异常
     */
    public static void commonExport(ExcelWriter writer, HttpServletResponse response) throws IOException {
        // 设置响应类型
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        // 设置字符编码
        response.setCharacterEncoding("utf-8");
        // 设置响应头信息
        response.setHeader("Content-disposition",
                "attachment;filename*=utf-8''" + URLEncoder.encode(new Date().getTime() +".xls", "utf-8"));
        try {
            ServletOutputStream out = response.getOutputStream();
            writer.flush(out, true);
            out.close();
        } finally {
            writer.close();
        }
    }

}
